﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using KJSyncXP.Sqlite.Model;
using KJSyncXP.ViewModels;
using Autofac;
using log4net;

namespace KJSyncXP.Extensions
{
    internal class AuthenticationManager : BaseViewModel
    {
        // 单例模式实现（线程安全）
        private static AuthenticationManager _instance;
        private static readonly object _lock = new object();

        // 会话与授权相关对象
        private Session _session;
        private AuthorizationVM _authorizationVM;
        private bool _isLogin;
        private bool _isReadonly = true;

        // 登录用户名
        public string LoginName
        {
            get
            {
                if (_session != null && _session.LoginUser != null)
                {
                    return _session.LoginUser.Username;
                }
                return string.Empty;
            }
        }

        // 当前登录用户
        public User CurrentUser
        {
            get { return (_session != null) ? _session.LoginUser : null; }
        }

        // 是否已登录
        public bool Logined
        {
            get { return _isLogin; }
            set
            {
                if (_isLogin != value)
                {
                    _isLogin = value;
                    RaisePropertyChanged("Logined");
                }
            }
        }

        // 是否只读模式
        public bool Readonly
        {
            get { return _isReadonly; }
            set
            {
                if (_isReadonly != value)
                {
                    _isReadonly = value;
                    RaisePropertyChanged("Readonly");
                }
            }
        }

        // 单例实例访问
        public static AuthenticationManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new AuthenticationManager();
                            _instance.Init();
                        }
                    }
                }
                return _instance;
            }
        }

        // 私有构造函数（单例模式）
        private AuthenticationManager() {

        }

        // 初始化方法
        private void Init()
        {
            if (_session == null)
            {
                _session = new Session();
                _session.PropertyChanged -= Session_PropertyChanged;
                _session.PropertyChanged += Session_PropertyChanged;
            }
        }

        // 会话属性变更事件处理
        private void Session_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "LoginUser")
            {
                if (_session.LoginUser != null)
                {
                    // 登录成功
                    Logined = true;
                    Readonly = false;
                    using (var scope = App._container.BeginLifetimeScope())
                    {
                        _authorizationVM = scope.Resolve<AuthorizationVM>();
                    }
                }
                // 初始化授权信息
                _authorizationVM.CurrentUser = _session.LoginUser;
                _authorizationVM.init();

                // 触发LoginName属性变更通知
                RaisePropertyChanged("LoginName");
            }
            else
            {
                Logined = false;
                Readonly = true;
                RaisePropertyChanged("LoginName");
            }
        }

        // 带密码的身份验证
        public bool Authenticate(string username, string passpwd)
        {
            Init();
            if (_session == null)
                return false;

            // 密码哈希处理
            //passpwd = CryptManager.HashPassword(passpwd);
            return _session.Login(username, passpwd);
        }


        // 权限验证（检查用户是否有指定操作权限）
        public bool authorize(string pkey)
        {
            if (_authorizationVM == null || _authorizationVM.Tokens == null)
                return false;

            return _authorizationVM.Tokens.Contains(pkey);
        }

        // 注销
        /*public void Logout()
        {
            if (_session != null)
                _session.Logout();

            if (_authorizationVM != null)
            {
                _authorizationVM.clear();
                // 释放授权对象（可选，根据实际需求）
                _authorizationVM = null;
            }
        }*/

        // 无密码的身份验证（如免密登录）
        /* public bool Authenticate(string username)
         {
             Init();
             if (_session == null)
                 return false;

             return _session.Login(username);
         }*/


    }
}
